/*
 * 
 * 
 * 
 */
package com.hboxs.asl.dao.impl;

import com.hboxs.asl.dao.OrderItemDao;
import com.hboxs.asl.entity.*;
import org.springframework.stereotype.Repository;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

/**
 * Dao - 订单项
 */
@Repository("orderItemDaoImpl")
public class OrderItemDaoImpl extends BaseDaoImpl<OrderItem, Long> implements OrderItemDao {

    @Override
    public Long count(Member member, Boolean hasReview) {

        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<OrderItem> criteriaQuery = criteriaBuilder.createQuery(OrderItem.class);
        Root<OrderItem> root = criteriaQuery.from(OrderItem.class);
        criteriaQuery.select(root);
        Predicate restrictions = criteriaBuilder.conjunction();
        if (member != null) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("order").get("member"), member));
        }
        if (hasReview != null) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("hasReview"), hasReview));
        }
        criteriaQuery.where(restrictions);
        return super.count(criteriaQuery, null);
    }

    @Override
    public OrderItem generate(Product product, CartItem cartItem, Order order) {
        OrderItem orderItem = new OrderItem();
        orderItem.setSn(product.getSn());
        orderItem.setName(product.getName() + "[" + product.getSpecValNames() + "]");
        orderItem.setFullName(product.getName());
        orderItem.setPrice(cartItem.getPrice());
        orderItem.setWeight(product.getWeight());
        orderItem.setThumbnail(product.getThumbnail());
        orderItem.setQuantity(cartItem.getQuantity());
        orderItem.setShippedQuantity(0);
        orderItem.setReturnQuantity(0);
        orderItem.setProduct(product);
        orderItem.setOrder(order);
        orderItem.setHasReview(false);
        orderItem.setHasApplyReturn(false);
        orderItem.setAnchor(cartItem.getAnchor());
        return orderItem;
    }

    @Override
    public List<OrderItem> findOrderItemsWithoutEvaluation(Order order) {
        String queryString = "SELECT orderItem FROM OrderItem AS orderItem " +
                "WHERE orderItem.order=:order AND orderItem.hasReview=false";
        return entityManager.createQuery(queryString).setParameter("order", order).getResultList();

    }
}